import { ref, computed, onMounted } from "vue"
import { message } from "ant-design-vue"
import { defineStore } from "pinia"
import { DataBaseApi } from "@/api"

export const useDataBaseStore = defineStore("dataBase", () => {
    const dbs = ref([])

    onMounted(() => {
        DataBaseApi.list()
            .then((res) => {
                if (res.status == 200) {
                    dbs.value = res.data
                } else {
                    message.error(res.data)
                }
            })
            .catch((err) => {
                message.error(err.message)
            })
    })

    const getItems = () => {
        let item = []
        for (let db of dbs.value) {
            item.push({ value: db.id, label: db.name })
        }
        return item
    }

    const getDbs = computed(() => {
        return dbs
    })

    const saveDataSource = (db) => {
        let addSign = true
        for (let o of dbs.value) {
            if (o.id == db.id) {
                o.name = db.name
                o.ip = db.ip
                o.serv = db.serv
                o.type = db.type
                o.user = db.user
                addSign = false
                break
            }
        }
        if (addSign) {
            dbs.value.push(db)
        }
    }
    const delDataSource = (id) => {
        for (let i in dbs.value) {
            if (dbs.value[i].id == id) {
                dbs.value.splice(i, 1)
                break
            }
        }
    }

    return { getDbs, getItems, saveDataSource, delDataSource }
})
